package com.bytedance.danmaku.render.engine.demo.demo


import android.os.Build
import android.util.Log
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatSeekBar
import com.bytedance.danmaku.render.engine.BaseDanmakuData
import com.bytedance.danmaku.render.engine.DanmakuView
import com.bytedance.danmaku.render.engine.control.DanmakuController
import com.bytedance.danmaku.render.engine.demo.R
import com.bytedance.danmaku.render.engine.demo.base.BaseDemoActivity
import com.bytedance.danmaku.render.engine.demo.utils.DanmakuDataProcessor
import com.bytedance.danmaku.render.engine.demo.utils.IVideoListener
import com.bytedance.danmaku.render.engine.demo.utils.toDisplayDuration

import com.bytedance.danmaku.render.engine.utils.Logger

import com.bytedance.danmaku.render.engine.render.layer.bottom.BottomCenterLayer
import com.bytedance.danmaku.render.engine.render.layer.scroll.ScrollLayer
import com.bytedance.danmaku.render.engine.render.layer.top.TopCenterLayer
import com.bytedance.danmaku.render.engine.utils.LAYER_TYPE_BOTTOM_CENTER
import com.bytedance.danmaku.render.engine.utils.LAYER_TYPE_SCROLL
import com.bytedance.danmaku.render.engine.utils.LAYER_TYPE_TOP_CENTER


/**
 * Created by dss886 on 2021/04/20.
 */
class TimelineSyncActivity : BaseDemoActivity(), IVideoListener {

    private lateinit var mController: DanmakuController
    private lateinit var mPlayIcon: ImageView
    private lateinit var mSeekBar: AppCompatSeekBar
    private lateinit var mTimeStart: TextView
    private lateinit var mTimeEnd: TextView
    private val danmakuDataProcessor=DanmakuDataProcessor(0)
    private var mIsSeeking: Boolean = false

    override fun getLayoutId(): Int {
        return R.layout.activity_timeline_sync
    }

    override fun init() {
        mPlayIcon = findViewById(R.id.play_icon)
        mTimeStart = findViewById(R.id.time_start)
        mTimeEnd = findViewById(R.id.time_end)
        mSeekBar = findViewById(R.id.seek_bar)
        mController = findViewById<DanmakuView>(R.id.danmaku_view).controller

        mController.config.scroll.lineCount=2
//        mController.config.scroll.bufferSize=100
//        mController.config.scroll.bufferMaxTime=60*10000
        mController.setData(mDanmakuData)
        mController.getDataManager().nextDanmakuShowAfter()
        mVideoView.videoListener = this
        val debug=Logger.isVerboseLoggable()
        Log.e("DEBUG45",debug.toString())

//        mController.setData(mDanmakuData)
//        val danmakuDataProcessor=DanmakuDataProcessor(10 * 60 * 1000L)
//        danmakuDataProcessor.loadInitialData(mDanmakuData)
//        val data=danmakuDataProcessor.getDanmakusForProgress(1)
//        mController.appendData(data)
        mController.config.scroll.lineCount=2
        mVideoView.videoListener = this
        mController.config.scroll.bufferSize=2
        // 1. 配置全局缓冲规则（仅保留当前时间窗口内的弹幕）
//        mController.config.common.apply {
//            // 缓冲池满时的丢弃规则：优先丢弃已过期或最旧的弹幕
//            bufferDiscardRule = { danmakuData ->
//                val data =danmakuData as BaseDanmakuData
//                when {
//                    // 已过期的弹幕优先级最低，直接丢弃
//                    danmakuData?.showAtTime ?: 0 + getShowDuration(data) < mController.mDataManager.queryPlayTime() -> Long.MIN_VALUE
//                    // 未来时间越远的弹幕越晚加载，优先丢弃
//                    else -> danmakuData?.showAtTime ?: Long.MAX_VALUE
//                }
//            }
//
//            // 缓冲过期规则：超出当前时间窗口的弹幕直接判定为过期
//            bufferExpireRule = { danmakuData, currentPlayTime ->
//                val data =danmakuData as BaseDanmakuData
//                val showDuration = getShowDuration(data)
//                val endTime = danmakuData?.showAtTime ?: 0 + showDuration
//                // 过期条件：已错过显示时间，或未来太久（超过2秒）
//                endTime < currentPlayTime || (danmakuData?.showAtTime ?: 0) > currentPlayTime + 500
//            }
//        }

        mPlayIcon.setOnClickListener {
            if (mVideoView.isPlaying) {
                mVideoView.pause()
            } else {
                mVideoView.start()
            }
        }
        mSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    mTimeStart.text = progress.toLong().toDisplayDuration(false)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                mIsSeeking = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                seekBar ?: return
                mIsSeeking = false
                mVideoView.seekTo(seekBar.progress)
            }
        })
    }
    fun getShowDuration(danmakuData: BaseDanmakuData?): Long {
        return when (danmakuData?.layerType) {
            LAYER_TYPE_SCROLL -> minOf(7000L, 5000L + danmakuData.content!!.length * 100)  // 最长8秒
            LAYER_TYPE_TOP_CENTER, LAYER_TYPE_BOTTOM_CENTER -> minOf(3000L, 2000L +danmakuData.content!!.length * 80)  // 最长3秒
            else -> 0L
        }
    }
    override fun onPrepared() {
        mTimeEnd.text = mVideoView.duration.toLong().toDisplayDuration(false)
        mSeekBar.max = mVideoView.duration
    }

    override fun onVideoStart() {
        mPlayIcon.setImageResource(R.drawable.ic_pause)
        mController.start()
    }

    override fun onVideoPause() {
        mPlayIcon.setImageResource(R.drawable.ic_play)
        mController.pause()
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onProgress(position: Long) {
        if (!mIsSeeking) {

            Log.e("当前视频进度","$position")
            mController.Time=mVideoView.currentPosition.toLong()
//            var data=mController.getDataManager().getQureyData()
//            mController.getDataManager().filterData(position)
//            mController.config.common.bufferDiscardRule = { danmakuData ->
//                // 计算弹幕显示时间与当前播放时间的差值绝对值，差值越小越不容易被丢弃
//                Math.abs(danmakuData?.showAtTime ?: 0L - mVideoView.currentPosition)
//            }

            Log.e("=======", "onProgress: $position")
            var currentPlayTime=position
            // 定义有效时间窗口：当前时间±1.5秒
            val timeWindow = 0L
            val start = position - timeWindow
            val end = position + timeWindow

            // 从数据源筛选符合窗口的弹幕（过滤过期/未到时间的）
            val newDanmakus = mDanmakuData.filter { danmaku ->
                val danmakuEndTime = danmaku.showAtTime + getShowDuration(danmaku)
                danmaku.showAtTime in start..end && danmakuEndTime <= mVideoView.duration
            }

            // 追加符合条件的弹幕（自动触发缓冲池清理）
            if (newDanmakus.isNotEmpty()) {
                mController.appendData(newDanmakus)
            }

            // 强制清理所有层的缓冲池（确保积压弹幕被丢弃）
            mController.mRenderEngine.mRenderLayers.forEach { layer ->
                when (layer) {
                    is ScrollLayer -> layer.mBuffer.trimBuffer(currentPlayTime)
                    is TopCenterLayer -> layer.mBuffer.trimBuffer(currentPlayTime)
                    is BottomCenterLayer -> layer.mBuffer.trimBuffer(currentPlayTime)
                }
            }
//            val data=danmakuDataProcessor.getDanmakusForProgress(position)
//            danmakuDataProcessor.appendData(data)
//            mController.appendData(data)
//            mController.pause()
//            mController.start(position)

            mSeekBar.progress = position.toInt()
            mTimeStart.text = position.toDisplayDuration(false)
        }
    }

    override fun onVideoCompletion() {
        mPlayIcon.setImageResource(R.drawable.ic_replay)
        mController.pause()
    }

    override fun onVideoError() {
        mPlayIcon.setImageResource(R.drawable.ic_play)
        mController.pause()
    }

    override fun onSeekTo() {
        mController.clear()
        if (mVideoView.isPlaying) {
            Log.e("拖动视频","${mVideoView.currentPosition.toLong()}")
            mController.pause()
            mController.start(mVideoView.currentPosition.toLong())
        }
    }

    override fun onBufferStart() {
        mController.pause()
    }

    override fun onBufferEnd() {
        mController.start(mVideoView.currentPosition.toLong())
    }

    override fun onRelease() {
        mController.stop()
    }

}